package com.base.controller.web;

import com.base.po.param.NetState;
import com.base.po.voip.SbdDetail;
import com.base.po.voip.Subscribers;
import com.base.po.voip.TxSbdIpf;
import com.base.service.SbdDetailService;
import com.base.service.SubscribersService;
import com.base.service.TxSbdIpfService;
import com.base.utils.DateUtil;
import com.base.utils.Page;
import com.base.utils.io.FileDownload;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
public class TxSbdIpfWebController {

    @Autowired
    private TxSbdIpfService txSbdIpfService;
    @Autowired
    private SbdDetailService sbdDetailService;
    @Autowired
    private SubscribersService subscribersService;


//    @Transactional
//    @RequestMapping("/ipfsbdSearch")
//    public NetState search(@ApiParam(value = "mobile") @RequestParam(required = false) String mobile, @ApiParam(value = "1.sbd 2.ipf 100.全部") @RequestParam Integer type, @ApiParam(value = "审核状态") @RequestParam Integer status, @ApiParam(value = "页码") @RequestParam Integer pageNo) throws Exception {
//        String subId = null;
//        if (!StringUtils.isEmpty(mobile)) {
//            Subscribers subscribers = subscribersService.selectBySubscribers(mobile, null);
//            if (subscribers != null) subId = subscribers.getId();
//        }
//        List<TxSbdIpf> txSbdIpfs = txSbdIpfService.searchBy(subId, type, status, pageNo);
//        Integer pageCount = txSbdIpfService.countBy(subId, type, status);
//        List<Map<String, Object>> mapList = Lists.newArrayList();
//        txSbdIpfs.forEach(item -> {
//            Map<String, Object> map = MapUtils.object2Map(item);
//            Subscribers sub = subscribersService.selectByPrimaryKey(item.getSubId());
//            map.put("mobile", sub.getMobile());
//            mapList.add(map);
//        });
//        NetState netState = new NetState(NetState.SUCCESS_CONN, "查询成功", mapList);
//        netState.setOtherJson(pageCount);
//        return netState;
//    }

    @RequestMapping("/txsbdipfSuccess")
    public synchronized NetState verify(Integer txId, Integer status) throws Exception {
        TxSbdIpf txSbdIpf = txSbdIpfService.selectByPrimaryKey(txId);
        if (txSbdIpf == null) return new NetState(NetState.FEAILED, "无法查询该ID记录");
        if (txSbdIpf.getStatement().equals(1) || txSbdIpf.getStatement().equals(2)) {
            return new NetState(NetState.FEAILED, "该记录已经进入终态");
        }
        switch (status) {
            case 1:
                txSbdIpf.setStatement(status);
                txSbdIpfService.updateByPrimaryKeySelective(txSbdIpf);
                break;
            case 2:
                txSbdIpf.setStatement(status);
                txSbdIpfService.updateByPrimaryKeySelective(txSbdIpf);
                //退钱
                if (txSbdIpf.getType().equals(1)) {
                    SbdDetail sbdDetail = new SbdDetail(null, txSbdIpf.getSubId(), "审核失败退回", "审核失败退回", txSbdIpf.getMoney(), 1, 1, new Date());
                    sbdDetailService.insertSelective(sbdDetail);
                }
                break;
        }
        return new NetState(NetState.SUCCESS_CONN, "审核成功");
    }

    @RequestMapping("/ipfsbdIndex")
    public ModelAndView dtDetailsIndex(HttpServletRequest request, Integer currentPageNo, Integer type, Integer status, String mobile, String createTime, Integer statustx) {
        Map<String, Object> map = new HashMap<>(); // 返回数据对象
        String adminUserId = (String) request.getSession().getAttribute("adminUserId");
        String beginTime = null;
        String endTime = null;
        if (createTime != null && !createTime.equals("")) {
            String[] str = createTime.split(" - ");
            beginTime = str[0];
            endTime = str[1];
        }
        if (statustx == null || statustx.equals(100)){
            statustx=null;
        }
        if (adminUserId == null) {
            return new ModelAndView("jsp/tx_jtx", map);
        }
        String userId = null;
        if (currentPageNo == null) currentPageNo = 1;

        if (!StringUtils.isEmpty(mobile)) {
            Subscribers sub = subscribersService.selectBySubscribers(mobile, adminUserId);
            if (sub == null) return new ModelAndView("jsp/tx_jtx", map);
            else userId = sub.getId();
        }

        // 设置分页 获取内容
        Page page = new Page(); // 实例化分页
        if (currentPageNo != null) page.setCurrentPageNo(currentPageNo); // 设置当前页
        page.setRecordTotal(txSbdIpfService.countBy(userId, type, statustx,beginTime,endTime,null,statustx)); // 设置总条数
        List<TxSbdIpf> refunds = txSbdIpfService.searchBy(userId, type, statustx,beginTime,endTime, page.getCurrentPageNo());

        for (TxSbdIpf dtRecording : refunds) {
            if (!StringUtils.isEmpty(dtRecording.getSubId())) {
                Subscribers sub = subscribersService.selectByPrimaryKey(dtRecording.getSubId());
                if (sub != null) dtRecording.setSubId(sub.getMobile());
            }
        }
        map.put("refundList", refunds); // 提现集合
        map.put("status", status);
        map.put("type", type);
        map.put("createTime",createTime);
        map.put("mobile", mobile);
        map.put("statustx",statustx);
        map.put("pages", page); // 分页
        map.put("curPage", page.getCurrentPageNo());
        return new ModelAndView("jsp/tx_jtx", map);
    }

    @RequestMapping(value = "/txSbdIpfExport", method = RequestMethod.POST)
    public void txSbdIpfExport(HttpServletRequest request, HttpServletResponse response,
                               String mobile, // 操作用户的id
                               Integer type,String createTime, Integer statustx) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Page page = new Page(); // 实例化分页

        Integer currentPageNo = 1;
        String userId = null;
        String beginTime = null;
        String endTime = null;
        if (createTime != null && !createTime.equals("")) {
            String[] str = createTime.split(" - ");
            beginTime = str[0];
            endTime = str[1];
        }
        if (statustx == null || statustx.equals(100)){
            statustx=null;
        }
        if (!StringUtils.isEmpty(mobile)) {
            Subscribers sub = subscribersService.selectBySubscribers(mobile, null);
            if (sub == null) {
                out.print("用户不存在");
                return;
            } else userId = sub.getId();
        }
        page.setRecordTotal(txSbdIpfService.countBy(userId, type, statustx,beginTime,endTime,null,statustx)); // 设置总条数
        List<TxSbdIpf> refunds = txSbdIpfService.searchByAll(userId, type, statustx,beginTime,endTime, page.getCurrentPageNo());

        for (TxSbdIpf dtRecording : refunds) {
            if (!StringUtils.isEmpty(dtRecording.getSubId())) {
                Subscribers sub = subscribersService.selectByPrimaryKey(dtRecording.getSubId());
                if (sub != null) dtRecording.setSubId(sub.getMobile());
            }
        }
        // 新建工作表
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("第" + (1) + "万条OEM数据");
        // 创建行,行号作为参数传递给createRow()方法,第一行从0开始计算
        HSSFRow title = sheet.createRow(0);
        HSSFCell tc0 = title.createCell(0);
        tc0.setCellValue("编号");
        HSSFCell tc1 = title.createCell(1);
        tc1.setCellValue("手机号");
        HSSFCell tc2 = title.createCell(2);
        tc2.setCellValue("创建时间");
        HSSFCell tc3 = title.createCell(3);
        tc3.setCellValue("提现金额");
        HSSFCell tc4 = title.createCell(4);
        tc4.setCellValue("提现地址");
        HSSFCell tc5 = title.createCell(5);
        tc5.setCellValue("审核状态");
        HSSFCell tc6 = title.createCell(6);
        tc6.setCellValue("目标地址");
        for (int i = 0; i < refunds.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            HSSFCell titlecell0 = row.createCell(0);
            titlecell0.setCellValue(refunds.get(i).getId());
            HSSFCell titlecell1 = row.createCell(1);
            titlecell1.setCellValue(refunds.get(i).getSubId());
            HSSFCell titlecell2 = row.createCell(2);
            titlecell2.setCellValue(DateUtil.dateToStrLong(refunds.get(i).getTx_time()));
            HSSFCell titlecell3 = row.createCell(3);
            titlecell3.setCellValue(refunds.get(i).getMoney().setScale(2, RoundingMode.HALF_EVEN).doubleValue());
            HSSFCell titlecell4 = row.createCell(4);
            titlecell4.setCellValue(0); //提现地址
            HSSFCell titlecell5 = row.createCell(5);
            if (refunds.get(i).getStatement().equals(1)) {
                titlecell5.setCellValue("已同意");
            } else if (refunds.get(i).getStatement().equals(0)) {
                titlecell5.setCellValue("待审核");
            } else if (refunds.get(i).getStatement().equals(2)) {
                titlecell5.setCellValue("拒绝");
            }
            HSSFCell titlecell6 = row.createCell(6);
            titlecell6.setCellValue(refunds.get(i).getTx_pack());
        }
        // 剩下部分导出
//		if (examplePage.start * 10000 != totlenum) {
//			examplePage.start += 1;
//			examplePage.rows = examplePage.pagesize;// 设置首次分页
//			if (users == null) {
//				users = new ArrayList<Subscribers>();
//			} else {
//				users.clear();
//			}
//			users = subscribersService.selectByExamplePage(examplePage);
//			// 新建工作表
//			HSSFSheet sheet = workbook.createSheet("第" + (examplePage.start + 1) + "万条用户信息");
//			for (int i = 0; i < users.size(); i++) {
//				HSSFRow row = sheet.createRow(i);
//				// 创建单元格,row已经确定了行号,列号作为参数传递给createCell(),第一列从0开始计算
//				HSSFCell cell = row.createCell(0);
//				// 设置单元格的值,即C1的值(第一行,第三列)
//				cell.setCellValue(users.get(i).getId());
//			}
//		}
        // 输出到磁盘中
        // FileOutputStream fos = new FileOutputStream(
        // new File("C:\\Users\\Administrator\\Desktop\\批次号" + batch +
        // "充值卡.xls"));
        response.setCharacterEncoding("utf-8");

        File file = null;

        String fileName=DateUtil.getNowDateStr()+"sbdIpf提现记录.xls";
        String tempDir=System.getProperty("java.io.tmpdir");
        String fileDir=tempDir+"/"+fileName;
        file = new File(fileDir);
        if (!file.exists()) {
            file.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        workbook.close();
        fos.close();
        FileDownload.fileDownload(response,fileDir,fileName);
    }
}
